package com.CommunityHub.kiana.controller;

import com.CommunityHub.kiana.po.HouseInfo;
import com.CommunityHub.kiana.po.User;
import com.CommunityHub.kiana.service.MemberService;
import com.CommunityHub.kiana.service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/HouseListServlet")
public class HouseListServlet extends HttpServlet {
    private MemberService memberService = new MemberService();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession(false);

        /*// 调试：打印请求URL和客户端IP
        System.out.println("[DEBUG] 收到请求: " + request.getRequestURL());
        System.out.println("[DEBUG] 客户端 IP: " + request.getRemoteAddr());*/

        // 检查用户登录状态
        if (session == null || session.getAttribute("user") == null) {
            System.out.println("[DEBUG] 用户未登录，跳转至登录页面");
            response.sendRedirect("login.jsp");
            return;
        }

        try {
            User user = (User) session.getAttribute("user");
            System.out.println("[DEBUG] 当前用户ID: " + user.getId());

            // 获取筛选参数
            String priceRange = request.getParameter("priceRange");
            String areaRange = request.getParameter("areaRange");
            String location = request.getParameter("location");

/* // 调试：输出接收到的参数
            System.out.println("[DEBUG] 接收到的筛选参数:");
            System.out.println("       priceRange = " + priceRange);
            System.out.println("       areaRange  = " + areaRange);
            System.out.println("       location   = " + location);*/


            List<HouseInfo> houses;

            // 判断是否有筛选条件
            if (hasFilterParams(priceRange, areaRange, location)) {
                /*System.out.println("[DEBUG] 正在根据筛选条件查询房源...");*/

                // 执行筛选查询
                houses = memberService.filterHouses(priceRange, areaRange, location);

                // 保存筛选条件到request，用于回显
                request.setAttribute("priceRange", priceRange);
                request.setAttribute("areaRange", areaRange);
                request.setAttribute("location", location);

            } else {
               /* System.out.println("[DEBUG] 无筛选条件，获取所有可售房源...");*/
                houses = memberService.getAvailableHouses();
            }

            // 获取会员购房状态
            boolean hasPurchased = memberService.hasPurchasedHouse(user.getId());
            /*System.out.println("[DEBUG] 用户是否已购房: " + hasPurchased);*/

            // 设置返回属性
            request.setAttribute("houses", houses);
            request.setAttribute("hasPurchased", hasPurchased);

            // 调试：输出查询结果数量
            if (houses != null) {
                System.out.println("[DEBUG] 查询结果数量: " + houses.size() + " 条");
            } else {
                System.out.println("[DEBUG] 查询结果为空");
            }

            // 转发到JSP页面
            request.getRequestDispatcher("houseList.jsp").forward(request, response);

        } catch (SQLException e) {
            // 输出错误堆栈信息以便定位问题
            e.printStackTrace();

            // 记录SQL异常并转发错误信息
            /*System.err.println("[ERROR] 加载房源数据失败: " + e.getMessage());*/
            request.setAttribute("error", "加载房源数据失败: " + e.getMessage());
            request.getRequestDispatcher("houseList.jsp").forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response); // 统一使用doGet处理
    }

    /**
     * 检查是否有筛选条件
     */
    private boolean hasFilterParams(String priceRange, String areaRange, String location) {
        boolean result =
                (priceRange != null && !priceRange.isEmpty() && !"不限".equals(priceRange)) ||
                        (areaRange != null && !areaRange.isEmpty() && !"不限".equals(areaRange)) ||
                        (location != null && !location.isEmpty() && !"不限".equals(location));

       /* System.out.println("[DEBUG] hasFilterParams 返回值: " + result);*/
        return result;
    }
}